<template>
  <div class="home">
    <van-swipe class="my-swipe" :autoplay="2000" indicator-color="white">
      <van-swipe-item v-for="item in banners" :key="item._id">
        <img :src="item.coverImg" alt="" />
      </van-swipe-item>
    </van-swipe>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <ul class="product">
        <li
          v-for="item in products"
          :key="item._id + Math.random()"
          @click="godetail(item._id)"
        >
          <img :src="item.coverImg" alt="" />
          <div class="product_r">
            <h3>{{ item.name }}</h3>
            <p>￥{{ item.price }}</p>
          </div>
        </li>
      </ul>
    </van-list>
  </div>
</template>

<script>
import { reqBanners, reqProducts } from "../../api/products";
export default {
  data() {
    return {
      banners: [],
      products: [],
      loading: false,
      page: 1,
      finished: false,
    };
  },
  methods: {
    async getProducts() {
      this.loading = true;
      const result = await reqProducts({ page: this.page });
      this.loading = false;
      this.products = [...this.products, ...result.products];
      if (result.products.length < 10) {
        this.finished = true;
      } else {
        this.page++;
      }
    },
    async initBanners() {
      const result = await reqBanners();
      console.log(result);
      this.banners = result.products;
    },
    onLoad() {
      this.initBanners();
      this.getProducts();
    },
    async initProducts() {
      const result = await reqProducts();
      console.log(result);
      this.products = result.products;
    },
    godetail(id) {
      this.$router.push("/detail/" + id);
    },
  },
  created() {
    this.initBanners();
    this.initProducts();
  },
};
</script>

<style scoped>
.van-swipe-item,
.my-swipe,
.van-swipe-item img {
  height: 220px;
}
.van-swipe-item img {
  width: 100%;
}
.home {
  padding-bottom: 40px;
}
.product li {
  display: flex;
  padding: 10px;
}
.product li img {
  width: 80px;
  height: 80px;
  display: block;
}
.product li .product_r {
  flex: 1;
  padding-left: 10px;
}
.product li .product_r h3 {
  font-size: 13px;
  color: #888;
}
.product li .product_r p {
  font-size: 10px;
  color: rgb(234, 74, 5);
}
</style>
